
package com.exam.api.modules.goods.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.exam.api.modules.goods.domain.TblProductInfo;
import com.exam.api.modules.goods.domain.TblProductSkuInfo;
import com.exam.api.modules.goods.utils.youzan.YZProduct;
import com.exam.api.modules.goods.utils.youzan.YZProductSku;
import com.exam.api.modules.goods.utils.youzan.YZRequest;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Profile("prod")
@Log4j2
public class ProductInfoSyncDataService  {

    @Resource
    private ThreadPoolTaskExecutor appExecutor;
    @Resource
    private YZRequest yzRequest;
    @Resource
    private TblProductSkuInfoService productSkuInfoService;
    @Resource
    private TblProductInfoService productInfoService;

    @Scheduled(fixedRate = 60, timeUnit = TimeUnit.MINUTES, initialDelay = 20)
    public void updateDict() {
        appExecutor.execute(this::refreshYzGoodsList);
    }

    @Transactional
    public void refreshYzGoodsList() {

        try {
            List<YZProduct> productList = yzRequest.getProductList();
            Map<Long,List<YZProductSku>> cache = new HashMap<>();
            productList.forEach(item -> {
                List<YZProductSku> productSkuList = yzRequest.getProductSkuList(item);
                cache.put(item.getItemId(),productSkuList);
            });

            if(CollUtil.isNotEmpty(productList)){
                productInfoService.lambdaUpdate().remove();
                List<TblProductInfo> tblProductInfos = BeanUtil.copyToList(productList, TblProductInfo.class);
                productInfoService.saveBatch(tblProductInfos);
                List<TblProductSkuInfo> skuInfos = new ArrayList<>();
                productList.forEach(item -> {
                    List<YZProductSku> yzProductSkus = cache.get(item.getItemId());
                    List<TblProductSkuInfo> skus = BeanUtil.copyToList(yzProductSkus, TblProductSkuInfo.class);
                    skus.forEach(sku -> sku.setProductId(item.getItemId()));
                    skuInfos.addAll(skus);
                });
                if(CollUtil.isNotEmpty(skuInfos)) {
                    productSkuInfoService.lambdaUpdate().remove();
                    productSkuInfoService.saveBatch(skuInfos);
                }
            }

        }catch (Exception e){
            log.error(e.getLocalizedMessage());
        }

    }
}
